package aqs;

import java.util.concurrent.CountDownLatch;

/**
 * 
 * 
 * @author insight
 * @since 2021/9/13
 */
public class MutexTest {
    private static volatile int v;
    private static Mutex mutex = new Mutex();

    public static void main(String[] args) throws InterruptedException {
        int thread = 100;
        // 保证所有线程同时开始 以及阻塞main线程 等待所有线程结束
        // 否则结果不正确
        CountDownLatch start = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(thread);

        for (int i = 0; i < thread; i++) {
            new Thread(() -> {
                try {
                    start.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int j = 0; j < 10; j++) {
                    mutex.lock();
                    try {
                        // idea 会提示这一步非原子操作 不过使用锁了不用担心
                        ++v;
                    } finally {
                        mutex.unlock();
                    }
                }
                end.countDown();
            }).start();
        }
        
        start.countDown();
        end.await();

        // 多次测试结果都是 1000
        System.out.println(v);
    }
}